package com.forcht.server.handler.impl;

import com.forcht.common.domain.Message;
import com.forcht.common.domain.MessageHeader;
import com.forcht.common.enumeration.ResponseCode;
import com.forcht.server.handler.MessageHandler;
import com.forcht.server.handler.UserHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

/**
 * Created by forcht on 2018/4/14.
 */
@Component("messageHandler.logout")
public class LogoutMessageHandler extends MessageHandler {

    @Autowired
    private UserHandler userHandler;

    @Override
    public void handle(Message message, SelectionKey key) {
        MessageHeader header = message.getHeader();
        String sender = header.getSender();
        userHandler.logout(sender);
        //通知好友用户下线
        userHandler.broadcast(sender, ResponseCode.FRIEND_LOGOUT);
        //等消息发送出去
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //关闭用户通道
        try {
            SocketChannel socketChannel = (SocketChannel) key.channel();
            key.cancel();
            socketChannel.socket().close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
